$(document).ready(function() {
	///// SET DEFAULT CSS CLASS FOR IMPROMPTU PLUGIN ///
	
	
});

/**
 * This file contains javascript to handle information of sale program.
 */
//////////////////////// LOADING A PAGE ////////////
function loadPage(sourceDiv, actionURL, compositeServiceId) {
      
    $.ajax ({       
        url:        actionURL + "?set_ajax_view",
        data:       "composite_service_id=" + compositeServiceId,      
        dataType:   "html",
        beforeSend: function() {
            $('div#pageContent').hide("slow");
            $('div#' + sourceDiv).hide("slow");         
        },
        complete:   function() {
            $('div#' + sourceDiv).show("fast");
        },
        success:  function(data) {
            $("#" + sourceDiv).html(data);
        }
    });
}

function changeCompositeServiceStatus(CSId, control) {
    $.ajax ({   
        url:        "changeCompositeServiceStatusAjax?set_ajax_view",
        data:       "CSId=" + CSId,
        success:  function(data) {
            csTable = $('#composite_service_list');
            var html = '';
            var status = '';
            if (control == 'lock') {
            	
                status = '<span class="impression" id="disable_' + CSId +'_span" islocked="1">' + _("Temporary lock") + '</span>';
                html = '<a class="btn" href="javascript:changeCompositeServiceStatus(' + CSId + ', \'unlock\');" title="' + _("Unlock composite service") + '">' 
                + '<img src="../images/unlock_small.png" alt="' + _("Unlock") + '"></img></a>';
            } else if (control == 'unlock') {
            	//#bug id: 643
                //status = '<span >Đang SD</span>';
            	//
            	//begin
                status = '<span id="disable_' + CSId +'_span" islocked="0">' + _("In use") + '</span>';
                //end
                html = '<a class="btn" href="javascript:changeCompositeServiceStatus(' + CSId + ', \'lock\');" title="' + _("Temporary lock composite service") + '">' 
                + '<img src="../images/lock_small.png" alt="' + _("Temporary lock") + '"></img></a>';
            }
            $('tr#'+ CSId + ' td:nth-child(4)', csTable).html(status);
            $('tr#'+ CSId + ' a.btn', csTable).parent().html(html);
            
        }
    });
}

function saveCS() {
    
    // refresh status_message
    $('#status_message').html("");
    // prepare data before saving
    
    // check composite_service_name
    if (!isNotEmpty($('#name'), _("Empty composite service name"), "status_message")) {
        return;
    }
    var submitData = $('#add_composite_service_form').formSerialize();
    // call controller to save data
    $.ajax({
        type:   "POST",
        url:    "../CompositeService/SaveCompositeServiceAjax?set_ajax_view",
        data:   submitData,
        beforeSend: function() {
            $('div#list_composite_service_container').hide();
            $('#barLoading').show();                
        },
        complete:   function() {
            $('#barLoading').hide();
            
        },
        success:    function(data) {
        	if(data == 1){
        		$('div#list_composite_service_container').show();
        		$('#status_message').text(_("Composite service existed")).show();
        		$('#name').css("border-color", "red");
        		return ;
        	}
        	loadPage('pageContent', 'AddCompositeService', '');
        }
    });   
}

function editCS(cs_id, cs_name, payment_type, room_name){
	$('div#add_form').fadeOut("fast");
	$('#status_message').text('').hide();
	$('#name').css("border-color", "#AAA");
	$('#composite_service_id').val(cs_id);
	$('#name').val(cs_name);
	$('#payment_select').val(payment_type);
	$('#room_select').val(room_name);
	var islocked = $('#disable_'+cs_id+'_span').attr("islocked");
	//#bug id 643
	//
	//if(disable_text == 'Đang SD'){
	//	$('input[@name="disabled"]')[1].checked = true;
	//	
	//}else{
	//	$('input[@name="disabled"]')[0].checked = true;
	//}
	////////////
	//begin fix
	if(islocked == '0'){
		$('input[name="disabled"]')[1].checked = true;
		
	}else{
		$('input[name="disabled"]')[0].checked = true;
	}
	//end
	$('#button_add').hide();
	$('#button_save').show();
	$('#button_cancel').show();
	$('div#add_form').fadeIn("slow");
	window.scrollTo(0,0);
}

function cancelCS() {
	$('div#add_form').fadeOut("fast");
	$('#status_message').text('').hide();
	$('#name').css("border-color", "#AAA");
	$('#composite_service_id').val('');
	$('#name').val('');
	//#bug id 777
	//$('input[@name="disabled"]')[1].checked = true;
	$('input[name="disabled"]')[1].checked = true;
	$('#button_add').show();
	$('#button_save').hide();
	$('#button_cancel').hide();
	$('div#add_form').fadeIn("slow");
}

// Add service into the mapped service list of current composite service
function addService() {

	//#0 Reset warning status
	$('span#status_message').html('');
	$('#serviceList').css('border-color', '#AAA');
	$('#serviceGroup').css('border-color', '#AAA');

	//#1 Validate serviceGroup
	if ( $('#serviceGroup').val() == "" ) {
		$('span#status_message').text(_('Please select service group.')).show();
		$('#serviceGroup').css('border-color', 'red');
		return;
	}

	var services = $('tr#services option:selected');

	//#2 Validate services
	if (services.length == 0)
	{
		$('span#status_message').text(_('Please select service.')).show();
		$('#serviceList').css('border-color', 'red');
		return;
	}
	
	var _serviceIds = new Array();
	var _serviceNames = new Array();
	var existedIndex = new Array();
	
	//#3 Check if this service is existed in the service list     
	for(i = 0; i < services.length; i++)
	{
		var serviceId = services[i].value;
		var serviceName = services[i].text;
    	
	    if ($.inArray(serviceId, serviceArray) >= 0) {
	    	existedIndex.push(i);
	        
	    } else {
			_serviceIds.push(serviceId);
			_serviceNames.push(serviceName);
	    }
    	
	}

	if(existedIndex.length > 0)
	{
		var existedServiceName = _("Existed: ");		
		for(i = 0; i < existedIndex.length; i++)
		{
			var index = existedIndex[i];
			var serviceName = services[index].text;
			
			existedServiceName +=  serviceName;
			
			if (i != existedIndex.length - 1) {
				existedServiceName += '; ';
			}
			
		}
		
		//$.prompt('Existed: <br>' + existedServiceName);
		$('span#status_message').text(existedServiceName).show();
		$('#serviceList').css('border-color', 'red');
		
		return;
	}
	
	if (_serviceIds.length == 0){
		return;
		
	}
    
    
    var _yes = "";
    var _no = "";
    if($('#required:checked').val() == "yes")
    {
    	_yes = ' checked="checked"';
    	
    } else {
    	_no = ' checked="checked"';
    	
    }
    
    // add these services into the services list
    for(i = 0; i < _serviceIds.length; i++)
	{
		var serviceId = _serviceIds[i];
    	var serviceName = _serviceNames[i];
    	
    	var valueId = 'value_' + serviceId;
	    var requiredId = 'required_' + serviceId;
	    var html = '<tr id="' + serviceId + '">'
	             + '<td>'
	             +     '<input type="hidden" id="serviceId[]" value="' + serviceId + '">'
	             +     '<span>' + serviceName + '</span>'
	             + '</td>'
	             
	             + '<td>'
	             +     '<input type="radio" id="' + requiredId + '" name="' + requiredId + '" value="no"' + _yes + '>' + _("Yes") 
	             +     '<input type="radio" id="' + requiredId + '" name="' + requiredId + '" value="yes"' + _no + '>' + _("No") 
	             + '</td>'
	             + '<td>'
	             +     '<a href="javascript:removeService(' + serviceId + ');" title="' + _("Delete service") + '">' 
	             +         '<img src="../images/remove_small.png" alt="' + _("Delete") + '"></img>'
	             +     '</a>'
	             + '</td>'
	             + '</tr>';
	    $('tbody', $('#mapped_service_list')).append(html);
	    serviceArray.push(serviceId);
	            
	    $('#mapped_service_list tr').removeClass('alt');
	    $('#mapped_service_list tr:even').addClass('alt');
	    $('#mapped_service_list').show();
    	
	}
	 
}

// Remove service from the mapped service list of current sale program
function removeService(serviceId) {
    $('#mapped_service_list tr#' + serviceId).nextAll().toggleClass('alt');
    $('#mapped_service_list tr#' + serviceId).remove();
    
    //Remove serviceId from serviceArray
    var temp = new Array();
    for(i = 0; i < serviceArray.length; i++)
    {
    	if (serviceArray[i] != serviceId)
    	{
    		temp.push(serviceArray[i]);
    	}	
    }
    serviceArray = temp ;
    
    if ($('#mapped_service_list tbody tr').length == 0) {
        $('#mapped_service_list').hide('medium');
    } 
}

// Save the mapping of composite service and service
function saveChoseService() {
    // refresh status_message
    $('#status_message').html("");
    
    // prepare data before saving
    var csServiceArr = new Array();   
    for (var i = 0; i < serviceArray.length; i++){
        
        // 'obj' contains serviceId, value, percent
        var obj = new Array();
        obj[0] = serviceArray[i];
        //#bug id 777
        //obj[1] = $("input[@name='required_" + serviceArray[i] + "']:checked").val();
        //
        //begin fix
        obj[1] = $("input[name='required_" + serviceArray[i] + "']:checked").val();        
        //end
  
        csServiceArr.push(obj);
    }
    // call controller to save data
    $.ajax({
        type:   "POST",
        url:    "../CompositeService/SaveChoseServiceAjax?set_ajax_view",
        data:   "composite_service_id=" + $('#composite_service option:selected').val() +
                "&cs_service_array=" + csServiceArr.join(';'),
        beforeSend: function() {
            $('#btn_save').hide();
            $('#barLoading').show();                
        },
        complete:   function() {
            $('#btn_save').show();
            $('#barLoading').hide();
        },
        success:    function(data) {
        
        }
    });
}

// 'serviceArray' is used to add/ remove service. This variable is initialized 
// when an item of 'sale_program' listbox is selected.
var serviceArray = new Array();

// Load the list of mapped service of the specific sale program.
function loadMappedService() {
    $.ajax ({       
        url:        "LoadMappedServiceAjax?set_ajax_view",
        data:       "composite_service_id=" + $('#composite_service option:selected').val(),
        dataType:   "json",
        success:  function(data) {
            table = $('#mapped_service_list');
            fillTableData(table, data.body);
            
            // INIT ROOM ARRAY  
            serviceArray = new Array();
	        $('#mapped_service_list tbody').children().each(function() {      
	            serviceArray.push($(this).attr('id'));         
	        });
	    }
    });
}

function fillTableData(table, data) {
    $('tbody', table).children().remove();
    $('tbody', table).append(data);
}
		
function getServices(){
	$('#status_message').html("");
	$('#serviceGroup').css("border-color", "#AAA");

	$.ajax({
        type:   "GET",
        url:    "../ServiceGroup/GetServicesByIdAjax?set_ajax_view",
        data:   "&groupId=" + $('#serviceGroup').val(),
        beforeSend: function() {
			$('#addService').hide();
			$('#serviceBarLoading').show();
			
        },
        complete:   function() {
            $('tr#services').show("fast");
            $('#addService').show();
            $('#serviceBarLoading').hide();
            
        },
        success:    function(data) {
        	$('tr#services').html(data);
        }
    });
	
}	






